package com.sunzr0119.conventioncentertemplatebackend.controller;

import com.mongodb.client.gridfs.model.GridFSFile;
import com.sunzr0119.conventioncentertemplatebackend.dto.SubmittedUser;
import com.sunzr0119.conventioncentertemplatebackend.dto.UploadFileDTO;
import com.sunzr0119.conventioncentertemplatebackend.entity.File;
import com.sunzr0119.conventioncentertemplatebackend.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/file-api")
public class FileController {

    private final GridFsTemplate gridFsTemplate;

    @Autowired
    private FileService fileService;

    public FileController(GridFsTemplate gridFsTemplate) {
        this.gridFsTemplate = gridFsTemplate;
    }

    @PostMapping("/upload")
    public ResponseEntity<UploadFileDTO> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("uploaderId") String uploaderId) {
        UploadFileDTO response = fileService.uploadFile(file, uploaderId);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/fileList/{userId}")
    public ResponseEntity<List<File>> fileList(@PathVariable String userId) {
        return fileService.getUsersFileList(userId);
    }

    @PostMapping("/delete/{fileId}")
    public void deleteFile(@PathVariable String fileId) {
        fileService.deleteFile(fileId);
    }

    @GetMapping("/getSubmittedUsers")
    public ResponseEntity<List<SubmittedUser>> getSubmittedUsers() {
        return fileService.getSubmittedUsers();
    }

    /**
     * 在线预览文件
     */
    @GetMapping("/preview/{fileId}")
    public ResponseEntity<Resource> previewFile(@PathVariable String fileId) {
        return fileService.getFileResource(fileId, false);
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{fileId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileId) {
        return fileService.getFileResource(fileId, true);
    }
}
